package route

import (
	"fmt"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/bean/httpBean"
	"gitee.com/gitee-go/core/bean/repobean"
	"gitee.com/gitee-go/core/common"
	"gitee.com/gitee-go/core/dbcore"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/core/models"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/server/engine"
	"gitee.com/gitee-go/server/service"
	"gitee.com/gitee-go/utils"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v2"
	"time"
)

type RepoController struct{}

func (RepoController) GetPath() string {
	return "/api/repo"
}
func (c *RepoController) Routes(g gin.IRoutes) {
	g.Use(service.MidUserCheck)
	g.POST("/builds", utils.GinReqParseJson(c.builds))
	g.POST("/param/users", utils.GinReqParseJson(c.users))
	g.POST("/param/pipeline", utils.GinReqParseJson(c.pipeline))
	g.POST("/param/branch", utils.GinReqParseJson(c.branch))
	g.POST("/param/branchSearch", utils.GinReqParseJson(c.branchSearch))
	g.POST("/param/events", c.events)
	g.POST("/param/status", c.status)
	g.POST("/getPipeline", utils.GinReqParseJson(c.getPipeline))
	g.POST("/getPipelines", utils.GinReqParseJson(c.getPipelines))
	g.POST("/branch/builds", utils.GinReqParseJson(c.getBranchBuilds))
	g.POST("/branch/branches", utils.GinReqParseJson(c.branches))
	g.POST("/branch/ymls", utils.GinReqParseJson(c.getYmlsFromBranch))
	g.POST("/getRepos", utils.GinReqParseJson(c.getRepos))
	g.POST("/refreshRepos", utils.GinReqParseJson(c.refreshRepos))
	g.POST("/repoDetail", utils.GinReqParseJson(c.repoDetail))
	g.POST("/activeRepo", utils.GinReqParseJson(c.activeRepo))
	g.POST("/closeRepo", utils.GinReqParseJson(c.closeRepo))
	g.POST("/setting/universal", utils.GinReqParseJson(c.universal))
	g.POST("/setting/visible", utils.GinReqParseJson(c.visible))
	g.POST("/setting/badge-url", utils.GinReqParseJson(c.badgUrl))
	g.POST("/setting/variables", utils.GinReqParseJson(c.variables))
	g.POST("/setting/saveVariable", utils.GinReqParseJson(c.saveVariable))
	g.POST("/setting/deleteVariables", utils.GinReqParseJson(c.deleteVariables))
}
func (RepoController) getPipeline(c *gin.Context, m *utils.Map) {
	repoId := m.GetString("repoId")
	id := m.GetString("id")
	if id == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	tp := &pipeline.TPipeline{}
	session := comm.DBMain.GetDB().Where("id = ?", id)
	if repoId != "" {
		session.Where("repo_id = ?", repoId)
	}
	_, err := session.Get(tp)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(tp).ResJson(c)
}
func (RepoController) getPipelines(c *gin.Context, m *utils.Map) {
	repoid := m.GetString("repoId")
	pg, _ := m.GetInt("page")
	sz, _ := m.GetInt("size")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	ls := make([]*models.TPipeline, 0)
	db := comm.DBMain.GetDB() // 查询Pipe分页
	ses := db.Cols("id,name,repo_id,display_name,display_name,pipeline_type").Where("repo_id = ? ", repoid)
	page, err := comm.DBMain.FindPage(ses, &ls, pg, sz)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	} // 查询
	sqls := "select pv.*,bd.* ,pv.status as tpv_status, bd.status as build_status FROM `t_pipeline_version` pv " +
		"left join `t_build` bd on bd.pipeline_version_id=pv.id" +
		" where pv.repo_id=? and pv.pipeline_id=? and pv.deleted !=1 " +
		"order by bd.created DESC limit 1"
	for _, v := range ls { // 把前端需要的信息查出来赋值(每一个流水线的最新一次运行状态,时间,等信息)
		spv := &models.ShowPipelineVersion{}
		get, err := db.SQL(sqls, repoid, v.Id).Get(spv)
		if err != nil || !get {
			continue
		}
		v.CommitMsg = spv.CommitMessage
		v.Created = spv.Created
		v.Status = spv.Status
		v.Started = spv.Started
		v.Finished = spv.Finished
		v.ExpendTime = int64(spv.Finished.Sub(spv.Started).Seconds())
		if v.Finished.IsZero() && !v.Started.IsZero() {
			v.ExpendTime = int64(time.Since(spv.Started).Seconds())
		}
		v.Status = spv.BuildStatus
		if spv.TpvStatus != common.PIPELINE_VERSION_STATUS_OK {
			v.Status = spv.TpvStatus
		}
	}
	core.NewUIResOk(page).ResJson(c)
}
func (RepoController) getBranchBuilds(c *gin.Context, m *utils.Map) {
	repoid := m.GetString("repoId")
	pipelineId := m.GetString("pipelineId")
	pg, _ := m.GetInt("page")
	sz, _ := m.GetInt("size")
	status := m.GetString("status")
	commitMsg := m.GetString("commitMsg")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	db := comm.DBMain.GetDB()
	repo := &pipeline.TRepo{}
	get, err := comm.DBMain.GetDB().Where("id =?", repoid).Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrNotFound).
			ResJson(c)
		return
	}
	var tvs []*pipeline.TPipelineVersion
	var args1 []interface{}
	args1 = append(args1, repoid) // 多参数查询
	sqld := "select {{select}} from (select DISTINCT(branch) from t_pipeline_version where repo_id =? "
	if pipelineId != "" {
		sqld += " and pipeline_id=? "
		args1 = append(args1, pipelineId)
	}
	sqld += " ) as t"
	page, err := comm.DBMain.FindPages(&dbcore.PageGen{
		SQL:       sqld,
		Args:      args1,
		CountCols: "branch",
		FindCols:  "branch",
	}, &tvs, pg, sz)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	ls := make([]*models.ShowPipelineVersion, 0)
	for _, v := range tvs {
		var args2 []interface{}
		args2 = append(args2, repoid)
		args2 = append(args2, v.Branch) // 多参数分页查询
		sqls := "select pv.*,bd.* ,pv.status as tpv_status , bd.status as build_status , pv.error as tpv_error " +
			"FROM `t_pipeline_version` pv " +
			"left join `t_build` bd on bd.pipeline_version_id=pv.id" +
			" where pv.repo_id=? and pv.branch=? and pv.deleted != 1 "
		if pipelineId != "" {
			sqls += " and pv.pipeline_id=? "
			args2 = append(args2, pipelineId)
		}
		if commitMsg != "" {
			sqls += " and (pv.commit_sha=? or pv.commit_message=?)"
			args2 = append(args2, commitMsg, commitMsg)
		}
		if status != "" {
			sqls += " and bd.status=? "
			args2 = append(args2, status)
		}
		if commitMsg != "" {
			sqls += " and (pv.commit_sha=? or pv.commit_message=?)"
			args2 = append(args2, commitMsg, commitMsg)
		}
		sqls += " order by bd.created DESC limit 1 "
		spv := &models.ShowPipelineVersion{}
		get, err = db.SQL(sqls, args2...).Get(spv)
		if err != nil || !get {
			continue
		}
		spv.CompletionFieldValue(repo)
		ls = append(ls, spv)
	}
	page.Data = ls
	core.NewUIResOk(page).ResJson(c)
}

func (RepoController) builds(c *gin.Context, m *utils.Map) {
	repoid := m.GetString("repoId")
	pipeid := m.GetString("pipelineId")
	branch := m.GetString("branch")
	events := m.GetString("events")
	status := m.GetString("status")
	commitSha := m.GetString("commitSha")
	commitMsg := m.GetString("commitMsg")
	uid := m.GetString("uid")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	repo := &pipeline.TRepo{}
	get, err := comm.DBMain.GetDB().Where("id= ?", repoid).Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrNotFound).
			ResJson(c)
		return
	}
	pg, _ := m.GetInt("page")
	sz, _ := m.GetInt("size")

	var args []interface{}
	ls := make([]*models.ShowPipelineVersion, 0)
	//ses:=comm.DBMain.GetDB().Join("JOIN","").Where("repo_id=?",repoid)
	//多参数分页查询
	sqls := "SELECT {{select}} FROM `t_pipeline_version` pv" +
		" left join `t_build` bd on bd.pipeline_version_id=pv.id" +
		" where pv.repo_id=? and pv.deleted != 1\n"
	args = append(args, repoid)
	if pipeid != "" {
		sqls += "and pv.pipeline_id=? \n"
		args = append(args, pipeid)
	}
	if branch != "" {
		sqls += "and pv.branch=? \n"
		args = append(args, branch)
	}
	if events != "" {
		if events == "build" {
			sqls += "and pv.trigger=? \n"
			args = append(args, "rebuild")
		} else {
			sqls += "and pv.events=? and pv.trigger=webhook  \n"
			args = append(args, events)
		}

	}
	if status != "" {
		sqls += "and bd.status=? \n"
		args = append(args, status)
	}
	if commitSha != "" {
		sqls += "and pv.commit_sha=? \n"
		args = append(args, commitSha)
	}
	if commitMsg != "" {
		sqls += "and pv.commit_message like ? \n"
		args = append(args, "%"+commitMsg+"%")
	}
	if uid != "" {
		sqls += "and pv.create_user_id=? \n"
		args = append(args, uid)
	}
	page, err := comm.DBMain.FindPages(&dbcore.PageGen{
		// 多参数分页查询
		SQL:       sqls + "ORDER BY create_time DESC",
		Args:      args,
		CountCols: "pv.id",
		FindCols:  "pv.*,pv.error as tpv_error, bd.`status`,bd.`error`, bd.started,bd.finished, pv.status as tpv_status , bd.status as build_status",
	}, &ls, pg, sz)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}

	for _, v := range ls {
		v.CompletionFieldValue(repo)
	}

	core.NewUIResOk(page).ResJson(c)
}

func (RepoController) pipeline(c *gin.Context, m *utils.Map) {
	rets := make([]*models.TPipelineInfo, 0)
	q := m.GetString("q")
	repoid := m.GetString("repoId")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	ses := comm.DBMain.GetDB().Where("repo_id = ?", repoid)
	if q != "" {
		lks := "%" + q + "%"
		ses.And("name like ? or display_name like ?", lks, lks)
		// 参数加入
	}
	err := ses.Find(&rets)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}

	core.NewUIResOk(rets).ResJson(c)
}

func (RepoController) users(c *gin.Context, m *utils.Map) {
	rets := make([]*models.SerchUser, 0)
	q := m.GetString("q")
	repoid := m.GetString("repoId")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	ses := comm.DBMain.GetDB().
		Where("id in(SELECT distinct(create_user_id) FROM `t_pipeline_version` pv where pv.repo_id=?)", repoid)
	// 查询
	if q != "" {
		lks := "%" + q + "%"
		ses.And("name like ? or nick like ?", lks, lks)
	}
	err := ses.Find(&rets)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}

	core.NewUIResOk(rets).ResJson(c)
}
func (RepoController) branch(c *gin.Context, m *utils.Map) {
	repoid := m.GetString("repoId")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	ls := make([]*models.ShowPipelineBranch, 0)
	err := comm.DBMain.GetDB().Select("DISTINCT(name)").
		Where("deleted !=1 and repo_id=?", repoid).
		Limit(50).Find(&ls)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(ls).ResJson(c)
}
func (RepoController) branchSearch(c *gin.Context, m *utils.Map) {
	repoid := m.GetString("repoId")
	q := m.GetString("q")
	if repoid == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	var ls1 []*models.ShowPipelineBranch
	var ls2 []*models.ShowPipelineVersion
	ls := make([]*httpBean.RepoBranchsRes, 0)

	ses := comm.DBMain.GetDB().Select("DISTINCT(name)").
		Where("deleted!=1 and repo_id=?", repoid)
	if q != "" {
		ses.And("name like ?", "%"+q+"%")
	}
	err := ses.Limit(50).Find(&ls1)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}

	for _, v := range ls1 {
		ls = append(ls, &httpBean.RepoBranchsRes{
			Type: "branch",
			Name: v.Name,
		})
	}
	if q != "" {
		// 如果需要搜索,就加入关键字查询
		err = comm.DBMain.GetDB().Select("DISTINCT(commit_sha)").
			Where("repo_id=? and deleted != 1 and commit_sha like ?", repoid, "%"+q+"%").
			Limit(50).Find(&ls2)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
		for _, v := range ls2 {
			ls = append(ls, &httpBean.RepoBranchsRes{
				Type: "commitSha",
				Name: v.CommitSha,
			})
		}
	}
	core.NewUIResOk(ls).ResJson(c)
}
func (RepoController) events(c *gin.Context) {
	core.NewUIResOk([]utils.Map{
		{"name": "push", "desc": "push"},
		{"name": "pr", "desc": "pr"},
		{"name": "comment", "desc": "评论"},
		{"name": "build", "desc": "手动"},
	}).ResJson(c)
}
func (RepoController) status(c *gin.Context) {
	core.NewUIResOk([]utils.Map{
		{"name": common.BUILD_STATUS_PENDING, "desc": "等待"},
		//{"name": common.BUILD_STATUS_READY, "desc": "准备"},
		{"name": common.BUILD_STATUS_RUNNING, "desc": "运行"},
		{"name": common.BUILD_STATUS_CANCEL, "desc": "取消"},
		{"name": common.BUILD_STATUS_ERROR, "desc": "错误"},
		{"name": common.BUILD_STATUS_OK, "desc": "完成"},
	}).ResJson(c)
}

func (RepoController) repoDetail(c *gin.Context, m *utils.Map) {
	openid := m.GetString("openid")
	if openid == "" {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("openid不能为空").
			ResJson(c)
		return
	}
	repo := &pipeline.TRepo{
		Openid:  openid,
		Deleted: 0,
	}
	db := comm.DBMain.GetDB()
	b, err := db.Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !b {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("未找到该仓库!").
			ResJson(c)
		return
	}
	core.NewUIResOk(repo).ResJson(c)
}
func (RepoController) closeRepo(c *gin.Context, m *utils.Map) {
	openid := m.GetString("openid")
	if openid == "" {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("openid不能为空").
			ResJson(c)
		return
	}
	user := service.GetMidLgUser(c)
	db := comm.DBMain.GetDB()
	tu := &pipeline.TUserToken{
		Uid: user.Id,
	}
	get, err := db.Get(tu)
	if err != nil {
		core.Log.Errorf("closeRepo err : %v", err)
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("服务异常！请重试").
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权!").
			ResJson(c)
		return
	}
	if tu.AccessToken == "" {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权!").
			ResJson(c)
		return
	}
	repo := &pipeline.TRepo{
		Openid:  openid,
		Deleted: 0,
	}
	b, err := db.Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !b {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("未找到该仓库!").
			ResJson(c)
		return
	}
	if repo.Active == 0 {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该仓库已关闭!").
			ResJson(c)
		return
	}
	err = service.CloseRepo(tu.AccessToken, repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk().ResJson(c)
}
func (RepoController) activeRepo(c *gin.Context, m *utils.Map) {
	openid := m.GetString("openid")
	if openid == "" {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("Openid不能为空").
			ResJson(c)
		return
	}
	user := service.GetMidLgUser(c)
	err := service.ActiveRepo(user, openid)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk().ResJson(c)
}

func (RepoController) refreshRepos(c *gin.Context) {
	if service.CheckCurrPermission(c, "admin") {
		core.NewUIResOk().ResJson(c)
		return
	}
	user := service.GetMidLgUser(c)
	db := comm.DBMain.GetDB()
	tu := &pipeline.TUserToken{
		Uid: user.Id,
	}
	get, err := db.Get(tu)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权").
			ResJson(c)
		return
	}
	if tu.AccessToken == "" {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权").
			ResJson(c)
		return
	}
	engine.Mgr().GetRefreshEgn().PutUid(user.Id)
	engine.Mgr().GetRefreshEgn().WaitUid(user.Id)
	core.NewUIResOk().ResJson(c)
}

func (RepoController) getRepos(c *gin.Context, param *repobean.ParamGetRepo) {
	user := service.GetMidLgUser(c)
	res, err := service.GetRepos(param, user)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(res).ResJson(c)
}
func (RepoController) universal(c *gin.Context, m *utils.Map) {
	id := m.GetString("repoId")
	if id == "" {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("仓库id不能为空").
			ResJson(c)
		return
	}
	db := comm.DBMain.GetDB()
	tr := &models.ShowSettingUniversal{}
	get, err := db.Where("id = ? and deleted != 1", id).Get(tr)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrNotFound).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(tr).ResJson(c)
}
func (RepoController) visible(c *gin.Context, m *utils.Map) {
	id := m.GetString("repoId")
	if id == "" {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("仓库id不能为空").
			ResJson(c)
		return
	}
	vis, err := m.GetInt("visible")
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if 0 > vis || vis > 2 {
		core.NewUIRes(common.UICodeErrParam).
			SetMsgObjs("未知的仓库状态").
			ResJson(c)
		return
	}
	db := comm.DBMain.GetDB()
	tr := &pipeline.TRepo{}
	tr.Visible = int(vis)
	_, err = db.Cols("visible").Where("id = ?", id).Update(tr)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk().ResJson(c)
}
func (RepoController) badgUrl(c *gin.Context, m *utils.Map) {
	repo := m.GetString("repo")
	pipe := m.GetString("pipeline")
	branch := m.GetString("branch")
	if repo == "" || pipe == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	ul := fmt.Sprintf("%s/badge/pipe/%s/%s/%s", comm.MainCfg.ServerConf.Host, repo, pipe, branch)
	core.NewUIResOk(ul).ResJson(c)
}
func (RepoController) variables(c *gin.Context, m *utils.Map) {
	repoId := m.GetString("repoId")
	q := m.GetString("q")
	types := m.GetString("types")
	field := m.GetString("field")
	sort := m.GetString("sort")
	if repoId == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	pg, _ := m.GetInt("page")
	sz, _ := m.GetInt("size")
	ls := make([]*pipeline.TRepoVariable, 0)
	session := comm.DBMain.GetDB().Where("repo_id = ?", repoId)
	if q != "" {
		session.And("(name like '%" + q + "%' or value like '%" + q + "%')")
	}
	if types != "" {
		if types != "public" {
			session.And("public !=0 ")
		} else if types != "readOnly" {
			session.And("read_only !=1 ")
		}
	}
	if field != "" && sort != "" {
		if field == "updateTime" {
			field = "update_time"
		}
		session.OrderBy(field + " " + sort)
	}
	page, err := comm.DBMain.FindPage(session, &ls, pg, sz)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(page).ResJson(c)
}

/**
保存流水线变量数据
1. 如果变量已存在就修改
2. 如果变量不存在就新增
*/
func (RepoController) saveVariable(c *gin.Context, repoVar *repobean.RepoVariable) {
	if repoVar.RepoId == "" || repoVar.Name == "" || repoVar.Value == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	err := repoVar.Check()
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	db := comm.DBMain.GetDB()
	tRepo := &pipeline.TRepo{}
	get, err := db.Where("id = ?", repoVar.RepoId).Get(tRepo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("未找到对应仓库").
			ResJson(c)
		return
	}
	if repoVar.Id == "" {
		rv := &pipeline.TRepoVariable{}
		get, err = db.Where("repo_id = ? and name = ?", tRepo.Id, repoVar.Name).Get(rv)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
		if get {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs("变量名重复").
				ResJson(c)
			return
		}
		rv.Id = utils.NewXid()
		rv.Name = repoVar.Name
		rv.Value = repoVar.Value
		rv.Remarks = repoVar.Remarks
		rv.CreateTime = time.Now()
		rv.UpdateTime = time.Now()
		rv.RepoId = tRepo.Id
		rv.Public = repoVar.Public
		rv.ReadOnly = repoVar.ReadOnly
		_, err = db.Insert(rv)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
	} else {
		rv := &pipeline.TRepoVariable{}
		get, err = db.Where("id = ?", repoVar.Id).Get(rv)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
		if !get {
			core.NewUIRes(common.UICodeErrNotFound).
				SetMsgObjs("变量不存在").
				ResJson(c)
			return
		}
		rv = &pipeline.TRepoVariable{}
		get, err = db.Where("repo_id = ? and name = ?", tRepo.Id, repoVar.Name).Get(rv)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
		if get && repoVar.Id != rv.Id {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs("变量名重复").
				ResJson(c)
			return
		}
		rv.Name = repoVar.Name
		rv.Value = repoVar.Value
		rv.Remarks = repoVar.Remarks
		rv.UpdateTime = time.Now()
		rv.Public = repoVar.Public
		rv.ReadOnly = repoVar.ReadOnly
		_, err = db.Where("id = ?", repoVar.Id).Cols("name,value,update_time,public,read_only,remarks").Update(rv)
		if err != nil {
			core.NewUIRes(common.UICodeErrs).
				SetMsgObjs(err).
				ResJson(c)
			return
		}
	}
	core.NewUIResOk().ResJson(c)
}
func (RepoController) deleteVariables(c *gin.Context, m *utils.Map) {
	id := m.GetString("id")
	if id == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	variable := &pipeline.TRepoVariable{}
	_, err := comm.DBMain.GetDB().Where("id = ?", id).Delete(variable)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk().ResJson(c)
}

// 通过分支获取yml文件
// 1. 获取登录用户
// 2. 获取仓库
// 3. 获取源仓库api
// 4. 调用api组装数据
func (RepoController) getYmlsFromBranch(c *gin.Context, m *utils.Map) {
	repoId := m.GetString("repoId")
	branch := m.GetString("branch")
	if repoId == "" || branch == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	user := service.GetMidLgUser(c)
	db := comm.DBMain.GetDB()
	tu := &pipeline.TUserToken{
		Uid: user.Id,
	}
	get, err := db.Get(tu)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get || tu.AccessToken == "" {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权").
			ResJson(c)
		return
	}
	repo := &pipeline.TRepo{}
	get, err = db.Where("id = ?", repoId).Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrNotFound).
			SetMsgObjs("仓库不存在").
			ResJson(c)
		return
	}
	appinfo, err := service.GetsParamOAuthKey()
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	k, info := appinfo.DefAppInfo()
	cl, err := comm.GetThirdApi(k, info.SourceHost)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	ymls, err := cl.Repositories.GetBranchYmls(tu.AccessToken, repo.Owner, repo.Name, comm.YamlDir, branch)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	ls := make([]*models.ShowBranchYmls, 0)
	for _, v := range ymls {
		sby := &models.ShowBranchYmls{}
		err := yaml.Unmarshal([]byte(v.Content), sby)
		if err != nil {
			core.Log.Errorf("getYmlsFromBranch Unmarshal err: %v", err)
			continue
		}
		sby.Content = v.Content
		sby.Sha = v.Sha
		sby.FileName = v.Name
		ls = append(ls, sby)
	}
	core.NewUIResOk(ls).ResJson(c)
}

// 获取仓库分支数据
// 1. 获取登录用户
// 2. 获取仓库
// 3. 获取源仓库api
// 4. 获取仓库分支
func (RepoController) branches(c *gin.Context, m *utils.Map) {
	repoId := m.GetString("repoId")
	if repoId == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	user := service.GetMidLgUser(c)
	db := comm.DBMain.GetDB()
	tu := &pipeline.TUserToken{
		Uid: user.Id,
	}
	get, err := db.Get(tu)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get || tu.AccessToken == "" {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("该用户未授权").
			ResJson(c)
		return
	}
	repo := &pipeline.TRepo{}
	get, err = db.Where("id = ?", repoId).Get(repo)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	if !get {
		core.NewUIRes(common.UICodeErrNotFound).
			SetMsgObjs("仓库不存在").
			ResJson(c)
		return
	}
	appinfo, err := service.GetsParamOAuthKey()
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	k, info := appinfo.DefAppInfo()
	cl, err := comm.GetThirdApi(k, info.SourceHost)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	branches, err := cl.Repositories.GetRepoBranches(tu.AccessToken, repo.Owner, repo.Name)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(branches).ResJson(c)
}
